package com.ruoyi.user.controller.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.file.FileSizeLimitExceededException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.system.domain.SpffVideos;
import com.ruoyi.system.service.ISpffVideosService;
import com.ruoyi.user.dto.Result;
import com.ruoyi.user.dto.VideoUploadDTO;
import com.ruoyi.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 视频Controller
 * 
 * @author xjj
 * @date 2025-09-11
 */
@RestController
@RequestMapping("/userApi/videos")
public class USpffVideosController extends BaseController
{
    @Autowired
    private ISpffVideosService spffVideosService;

    @Autowired
    private IUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询视频列表
     */
    @GetMapping("/list")
    public AjaxResult list(SpffVideos spffVideos)
    {
        startPage();
        List<SpffVideos> list = spffVideosService.selectSpffVideosList(spffVideos);
        return success(getDataTable(list));
    }

    /**
     * 导出视频列表
     */
    @Log(title = "视频", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SpffVideos spffVideos)
    {
        List<SpffVideos> list = spffVideosService.selectSpffVideosList(spffVideos);
        ExcelUtil<SpffVideos> util = new ExcelUtil<SpffVideos>(SpffVideos.class);
        util.exportExcel(response, list, "视频数据");
    }

    /**
     * 获取视频详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id, HttpServletRequest request)
    {
        SpffVideos video = spffVideosService.selectSpffVideosById(id);
        if (video == null) {
            return error("视频不存在");
        }
        
        // 获取当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null) {
            Long currentUserId = loginUser.getUserId();
            // 查询是否已关注视频作者
            AjaxResult followResult = userService.isFollowing(currentUserId, video.getUserId());
            // isFollowing方法直接返回包含isFollowing字段的Map
            if (followResult != null && followResult.get(AjaxResult.DATA_TAG) != null) {
                Map<String, Object> followData = (Map<String, Object>) followResult.get(AjaxResult.DATA_TAG);
                Boolean isFollowing = (Boolean) followData.get("isFollowing");
                video.setIsFollow(isFollowing != null ? isFollowing : false);
            } else {
                video.setIsFollow(false);
            }
        }

        
        return success(video);
    }

    /**
     * 新增视频
     */

    @Log(title = "视频", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpffVideos spffVideos)
    {
        return toAjax(spffVideosService.insertSpffVideos(spffVideos));
    }

    /**
     * 修改视频
     */
    @Log(title = "视频", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpffVideos spffVideos)
    {
        return toAjax(spffVideosService.updateSpffVideos(spffVideos));
    }

    /**
     * 删除视频
     */

    @Log(title = "视频", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(spffVideosService.deleteSpffVideosByIds(ids));
    }

//    /**
//     * 上传视频文件
//     */
//    @Log(title = "视频", businessType = BusinessType.INSERT)
//    @PostMapping("/upload")
//    public AjaxResult uploadVideo(SpffVideos videoUploadDTO) {
//        try {
//
//            // 构建视频对象
//            SpffVideos video = new SpffVideos();
//            // 优先使用DTO中的用户ID，如果没有则使用当前登录用户ID
//            if (videoUploadDTO.getUserId() != null) {
//                video.setUserId(videoUploadDTO.getUserId());
//            } else {
//                video.setUserId(SecurityUtils.getUserId()); // 获取当前登录用户ID
//            }
//            video.setTitle(videoUploadDTO.getTitle());
//            video.setDescription(videoUploadDTO.getDescription());
//            video.setVideoUrl(videoUploadDTO.getVideoUrl());
//            video.setCoverUrl(videoUploadDTO.getCoverUrl());
//            video.setTags(videoUploadDTO.getTags());
//            video.setCategoryId(videoUploadDTO.getCategoryId());
//            video.setLocation(videoUploadDTO.getLocation());
//            video.setStatus(1); // 设置为正常状态
//
//            // 保存视频信息
//            return toAjax(spffVideosService.insertSpffVideos(video));
//        } catch (FileSizeLimitExceededException e) {
//            return error("文件大小超出限制");
//        } catch (Exception e) {
//            return error("上传失败，请稍后再试");
//        }
//    }
    
//    /**
//     * 上传视频文件（仅视频文件）
//     */
//    @Log(title = "视频", businessType = BusinessType.INSERT)
//    @PostMapping("/uploadVideo")
//    public AjaxResult uploadVideoFile(@RequestParam("videoFile") MultipartFile videoFile) {
//        try {
//            // 上传视频文件
//            String videoUrl = FileUploadUtils.upload(videoFile, MimeTypeUtils.VIDEO_EXTENSION);
//            return success(videoUrl);
//        } catch (FileSizeLimitExceededException e) {
//            return error("文件大小超出限制");
//        } catch (InvalidExtensionException e) {
//            return error("文件格式不正确");
//        } catch (Exception e) {
//            return error("上传失败，请稍后再试");
//        }
//    }
    
//    /**
//     * 上传封面文件
//     */
//    @Log(title = "视频", businessType = BusinessType.INSERT)
//    @PostMapping("/uploadCover")
//    public AjaxResult uploadCoverFile(@RequestParam("coverFile") MultipartFile coverFile) {
//        try {
//            // 上传封面文件
//            String coverUrl = FileUploadUtils.upload(coverFile, MimeTypeUtils.IMAGE_EXTENSION);
//            return success(coverUrl);
//        } catch (FileSizeLimitExceededException e) {
//            return error("文件大小超出限制");
//        } catch (InvalidExtensionException e) {
//            return error("文件格式不正确");
//        } catch (Exception e) {
//            return error("上传失败，请稍后再试");
//        }
//    }
}
